<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\BaseController;
use App\Models\WechatMch;
use App\Models\WechatSet;

/***
 * Class AdminController
 * @package App\Http\Controllers\Admin
 * 后台管理员
 */
class WechatController extends BaseController
{

    public function __construct(WechatSet $wechatSet, WechatMch $wechatMch)
    {
        parent::__construct();
        $this->wechatSet = $wechatSet;
        $this->wechatMch = $wechatMch;
    }

    public function getIndex()
    {
        $data = $this->wechatSet->getOne();
        return view('admin.wechat.index', compact('data'));
    }

    public function postUpdate(Request $request)
    {
        $where['id'] = 2;
        $data = $request->except('_token');
        $res = $this->wechatSet->updateOrCreate($where, $data);
        if(!$res)
        {
            return redirect()->back()->with('status', '提交失败！ :(');
        }
        $key = 'yun_wechat_set';
        $this->wechatSet->delMc($key);
        return redirect()->back()->with('status', '提交成功！ :)');
    }

    public function getPaySet()
    {
        $data = $this->model->getOne();
        return view('admin.mch.edit', compact('data'));
    }

    public function postPaySet(Request $request)
    {
        $where['id'] = 2;
        $data = $request->only('mch_id', 'mch_key');

        $cert_path = $this->upBook($request, 'cert_path');
        $cert_path ? $data['cert_path'] = $cert_path : '';

        $key_path = $this->upBook($request, 'key_path');
        $key_path ? $data['key_path'] = $key_path : '';

        $res = $this->model->updateOrCreate($where, $data);
        if(!$res)
        {
            return redirect()->back()->with('status', '提交失败！ :(');
        }
        $key = 'yun_wechat_mch';
        $this->model->delMc($key);
        return redirect()->back()->with('status', '提交成功！ :)');
    }

    //证书上传
    public function upBook($request, $file)
    {
        $bookdir = '';
        if($request->hasFile($file))
        {
            $file = $request->file($file);
            if($file->isValid())
            {
                $destPath = 'uploads/book';
                if(!file_exists($destPath))
                {
                    mkdir($destPath, 0755, true);
                }
                $filename = $file->getClientOriginalName();
                $file->move($destPath, $filename);
            }
            $bookdir = $destPath.'/'.$filename;
        }
        return $bookdir;
    }
}